//
//  SZLAddressBookViewController.m
//  Shengzhuli
//
//  Created by 卡忙科技 on 16/11/12.
//  Copyright © 2016年 kamangkeji. All rights reserved.
//

#import "SZLAddressBookViewController.h"
#import <AddressBook/AddressBook.h>
#import "AddressBookModel.h"
#import "AddressBookCell.h"
#import "WineFriendsNetwork.h"
#import "SZLAccountHelper.h"
#import "MBProgressHUD+MJ.h"

@interface SZLAddressBookViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) NSMutableArray *addresses;
@property (nonatomic,strong) UITableView *sourceTab;

@end

@implementation SZLAddressBookViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"手机联系人";
    self.view.backgroundColor = [UIColor whiteColor];
    [self getAddreeBook];
}

- (void)getAddreeBook
{
    ABAddressBookRef addressBookref = ABAddressBookCreateWithOptions(NULL, NULL);
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
        ABAddressBookRequestAccessWithCompletion(addressBookref, ^(bool granted, CFErrorRef error) {
            CFErrorRef *error1 = NULL;
            ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error1);
            [self copyAddressBook:addressBook];
        });
    }else if(ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized){
        CFErrorRef *error1 = NULL;
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error1);
        [self copyAddressBook:addressBook];
        
    }else{
        UIAlertView *alert  = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有获取通讯录权限" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
        alert.delegate = self;
        [alert show];
    }
    CFRelease(addressBookref);
}
- (void)copyAddressBook:(ABAddressBookRef)addressBook{
    //获取联系人个数
    CFIndex numberOfPeoples = ABAddressBookGetPersonCount(addressBook);
    CFArrayRef peoples = ABAddressBookCopyArrayOfAllPeople(addressBook);
    NSLog(@"有%ld个联系人", numberOfPeoples);
    //循环获取联系人
    for (int i = 0; i < numberOfPeoples; i++) {
        ABRecordRef person = CFArrayGetValueAtIndex(peoples, i);
        AddressBookModel *linkMan = [[AddressBookModel alloc] init];
        linkMan.firstName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
        linkMan.lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
        linkMan.nickName = (__bridge NSString*)ABRecordCopyValue(person, kABPersonNicknameProperty);
        linkMan.organiztion = (__bridge NSString*)ABRecordCopyValue(person, kABPersonOrganizationProperty);
        linkMan.headImage = (__bridge NSData*)ABPersonCopyImageData(person);
        if (linkMan.firstName && linkMan.lastName) {
            linkMan.name = [NSString stringWithFormat:@"%@%@",linkMan.lastName, linkMan.firstName];
        }else if(!linkMan.firstName){
            linkMan.name = linkMan.lastName;
        }else{
            linkMan.name = linkMan.firstName;
        }
        if (!linkMan.name) {
            linkMan.name = linkMan.organiztion;
        }
        if (linkMan.nickName) {
            linkMan.name =[NSString stringWithFormat:@"%@", linkMan.nickName];
        }
        //读取电话多值
        NSMutableArray *phoneArray = [[NSMutableArray alloc] init];
        ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
        for (int k = 0; k<ABMultiValueGetCount(phones); k++)
        {
            NSString * tempstr = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phones, k);
            //去除数字以外的字符
            NSCharacterSet *setToRemove = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"]
                                           invertedSet];
            NSString *strPhone = [[tempstr componentsSeparatedByCharactersInSet:setToRemove] componentsJoinedByString:@""];
            [phoneArray addObject:strPhone];
            
            [phoneArray addObject:tempstr];
        }
        linkMan.phones = phoneArray;
        [self.addresses addObject:linkMan];
    }
    [self uploadAddressBook];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.addresses.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AddressBookCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AddressBookCell class])];
    cell.model = self.addresses[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    __WEAK
    cell.actionBlock = ^(UIButton *btn,AddressBookModel *model){
        if (model.status == 1) {
            [weakSelf invitateAddressBook:model btn:btn];
        }else if (model.status == 3){
            [weakSelf addFriends:model btn:btn];
        }
    };
    return cell;
}

#pragma mark -------------请求相关-------------------
- (void)uploadAddressBook
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    NSMutableArray *jsonArr = [NSMutableArray array];
    for (AddressBookModel *model in self.addresses) {
        if (model.phones.count == 0) {
            break;
        }
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"contactName"] = model.name;
        dict[@"contactPhone"] = model.phones[0];
        [jsonArr addObject:dict];
    }
    parame[@"addressBook"] = [[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:jsonArr options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
    [WineFriendsNetwork uploadAddressBookWithParame:parame response:^(BOOL success, NSString *msg, NSArray *addresses) {
        if (success) {
            [self.addresses removeAllObjects];
            [self.addresses addObjectsFromArray:addresses];
            [self.view addSubview:self.sourceTab];
        }else{
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}
- (void)invitateAddressBook:(AddressBookModel *)model btn:(UIButton *)btn
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"mobilePhone"] = model.contactPhone;
    [self showWaiter];
    [WineFriendsNetwork invitationWithParame:parame response:^(BOOL success, NSString *msg) {
        [self hideWaiter];
        if (success) {
            [MBProgressHUD showOnlyText:@"成功发送短信邀请" view:self.view];
            [btn setTitle:@"已发送短信邀请" forState:UIControlStateNormal];
            btn.enabled = NO;
            btn.backgroundColor = [UIColor clearColor];
            [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        }else{
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}
- (void)addFriends:(AddressBookModel *)model btn:(UIButton *)btn
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"token"] = [SZLAccountHelper shareInstance].token;
    params[@"friendMobilePhone"] = model.contactPhone;
    __WEAK
    [self showWaiter];
    [WineFriendsNetwork applyAddFriendsWithParame:params response:^(BOOL success, NSString *msg) {
        [weakSelf hideWaiter];
        if (success) {
            [MBProgressHUD showOnlyText:@"成功发送酒友申请" view:self.view];
            [btn setTitle:@"已发送酒友申请" forState:UIControlStateNormal];
            btn.enabled = YES;
            btn.backgroundColor = [UIColor clearColor];
            [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        }else{
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}

- (UITableView *)sourceTab
{
    if (!_sourceTab) {
        _sourceTab = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH-64)];
        _sourceTab.dataSource = self;
        _sourceTab.delegate = self;
        _sourceTab.rowHeight = 50;
        [_sourceTab registerNib:[UINib nibWithNibName:NSStringFromClass([AddressBookCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([AddressBookCell class])];
        _sourceTab.tableFooterView = [[UIView alloc]init];
    }
    return _sourceTab;
}

- (NSMutableArray *)addresses
{
    if (!_addresses) {
        _addresses = [NSMutableArray array];
    }
    return _addresses;
}
@end
